<?php namespace Phpcmf\Controllers\Admin;

class Home extends \Phpcmf\App
{
//admin.php?s=cut&c=home&m=index
    public function index()
    {

        $name = 'hello word';

        // 将变量传入模板
        \Phpcmf\Service::V()->assign([
            'testname' => $name,
        ]);
        // 选择输出模板 后台位于 ./Views/test.html 此文件已经创建好了
        \Phpcmf\Service::V()->display('show_list.html');
    }

//admin.php?s=cut&c=home&m=get_img_info
    public function get_img_info()
    {
        $file_path = $_GET['path'];
        $attachment = explode('/', $file_path);
        $len = count($attachment);
        $attachment = $attachment[$len - 2] . '/' . $attachment[$len - 1];
        $attachment_data_table = \Phpcmf\Service::M()->table('attachment_data');
        $attachment_data_table_item = $attachment_data_table->where('attachment', $attachment)->getAll();
        if (count($attachment_data_table_item) == 0) {
            $this->_json(1, '这个文件不是用户上传的');
            exit();
        }
        $info = $attachment_data_table_item[0];
        $this->_json(1, 'ok', json_encode($info));
    }


    // 验证权限脚本
    public function _check_upload_auth($editor = 0)
    {

        $error = '';
        if (!IS_API_HTTP && defined('SYS_CSRF') && SYS_CSRF && dr_get_csrf_token() != (string)$_POST['token']) {
            $error = '跨站验证禁止上传文件';
        } elseif ($this->member && $this->member['is_admin']) {
            return;
        } elseif (!\Phpcmf\Service::M('member_auth')->member_auth('uploadfile', $this->member)) {
            $error = '您的用户组不允许上传文件';
        } elseif (dr_is_app('mfile') && \Phpcmf\Service::M('mfile', 'mfile')->check_upload($this->uid)) {
            $error = '用户存储空间已满';
        }

        if ($error) {
            if ($editor) {
                return $error;
            } else {
                $this->_json(0, $error);
            }
        }

        return;
    }

    // 验证上传权限，并获取上传参数
    private function _get_upload_params()
    {

        // 验证用户权限
        $rt = \Phpcmf\Service::M('Attachment')->check($this->member, $this->siteid);
        if (!$rt['code']) {
            exit(dr_array2string($rt));
        }

        $fid = (int)\Phpcmf\Service::L('input')->get('fid');
        $field = \Phpcmf\Service::C()->get_cache('table-field', $fid);
        if (!$field) {
            $p = dr_string2array(dr_authcode(\Phpcmf\Service::L('input')->get('p'), 'DECODE'));
            if (!$p) {
                $this->_json(0, dr_lang('字段参数有误'));
            }
            return $p;
        }

        return [
            'size' => ($field['setting']['option']['size']),
            'exts' => $field['setting']['option']['ext'],
            'count' => max(1, (int)$field['setting']['option']['count']),
            'attachment' => $field['setting']['option']['attachment'],
            'image_reduce' => $field['setting']['option']['image_reduce'],
            'chunk' => $field['setting']['option']['chunk'] ? 20 * 1024 * 1024 : 0,
        ];
    }

//    admin.php?s=cut&c=home&m=upload_file
    public function upload_file($config)
    {

        return dr_return_data(1, 'ok', [
            'ext' => $config['fileext'],
            'url' => SYS_UPLOAD_PATH . $config['attachment'],
            'md5' => md5_file(SYS_UPLOAD_PATH . $config['attachment']),
            'file' => $config['attachment'],
            'size' => $config['filesize'],
            'path' => SYS_UPLOAD_PATH . $config['attachment'],
            'name' => $config['filename'],
            'info' => json_decode($config['attachinfo'], true),
            'remote' => $config['remote'] || 0,
        ]);
    }

//admin.php?s=cut&c=home&m=upload_cut_data
    public function upload_cut_data()
    {
//        TODO：将post请求序列化
//            TODO：处理请求
        $this->_check_upload_auth();
        $pos_json = '';
        $file_id = '';
        $value = '';
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            $pos_json = $_GET["value"];
            $value = json_decode($pos_json);
            $file_id = $value->id;
        } else {

            $pos_json = json_encode($_POST["value"]);
            $value = json_decode($pos_json);
            $file_id = $_POST['id'];
        }
        if (!$pos_json) {
            $this->_json(0, dr_lang('提交的数据错误'));
            exit();
        }
        //TODO：唯一性查询
        $attachment_data_table = \Phpcmf\Service::M()->table('attachment_data');
        $attachment_data_result = $attachment_data_table->getAll();
        //TODO：确定主键怎么写

        $id = $attachment_data_result[count($attachment_data_result) - 1]['id'];
        $id++;
        $attachment_data_table = $attachment_data_table->where('id', $file_id);
        $attachment_data_result = $attachment_data_table->getAll();

        if (count($attachment_data_result) == 0) {
            $this->_json(0, dr_lang('没有这个附件'));
            exit();
        }
//        TODO:数据库操作
//         TODO:补全这一项的表数据,增加一个逻辑附件
        $attachment_data_result_item = $attachment_data_result[0];
        $attachment_data_table = \Phpcmf\Service::M()->table('dr_attachment_data');
        $attachment_data_result_item['cutinfo'] = $pos_json;
        $rt = [
            $attachment_data_result_item
        ];
//        TODO:修改文件名
        if ($rt[0] && $rt[0]['cutinfo']) {
            $this->alert_file_name($rt[0]);
        }
        //        TODO:把路径改成新的路径
        if ($rt[0] && $rt[0]['attachment']) {
            $this->alert_attachment_info($rt[0]);
        }
        if (true ||
            $attachment_data_result_item['cutinfo'] == '0' ||
            $attachment_data_result_item['cutinfo'] == '{}'
        ) {
            //            TODO：真实附件
            //TODO:新的一个插件插入
            //TODO：数据库插入操作
            $rt[0]['id'] = $id;
            $rt = $this->upload_file($rt[0]);
            $data = \Phpcmf\Service::M('Attachment')->save_data($rt['data']);
            if (!$data['code']) {
                exit(dr_array2string($data));
            }

            // 上传成功
            if (IS_API_HTTP) {
                $data['data'] = [
                    'id' => $data['code'],
                    'url' => $rt['data']['url'],
                ];
                exit(dr_array2string($data));
            } else {
//            TODO：逻辑附件
                //              TODO:更新操作
                $attachment_data_table->update($rt[0]['id'], $rt[0]);
            }
//        TODO:返回
            $this->_json(1, dr_lang('截图成功'));
        }
    }

    private function alert_attachment_info(&$rt)
    {
        if (defined('NEW_FILE')) {
            $file_info = explode('/', NEW_FILE);
//            父一级
            $len = count($file_info);
            $parent_file = $file_info[$len - 2] . '/' . $file_info[$len - 1];
            $rt['attachment'] = $parent_file;

        } else {
            $this->_json(1, '缺少上传文件');
        }
    }
    //admin.php?s=cut&c=home&m=cut_photo
    // 剪切图片的功能
//    TODO:这是一个渲染函数
    public function cut_photo()
    {
//        TODO:请求数据，组件提交上来的
        $user_id = $_SESSION['uid'];
//        TODO:客户端文件名
        $pure_file = $_GET['name'];
//        $token = $_GET['token'];
//        TODO：文件名操作
        $ext_index = strpos($pure_file, '.');
        $file_ext = '';
        if ($ext_index) {
            $file_ext = substr($pure_file, $ext_index);
            $pure_file = str_replace($file_ext, '', $pure_file);
        }
//        TODO:数据库操作
//        TODO:附件表操作
        $attachment_data_table = \Phpcmf\Service::M()->table('attachment_data');
        $attachment_data_table = $attachment_data_table->where('uid', $user_id);
        $attachment_data_table = $attachment_data_table->where('filename', $pure_file);
        $aim_result_row = $attachment_data_table->where_in('fileext', $file_ext)->getAll();
//        TODO:最后一次上传的文件
//        TODO:这样做可能会有问题
        $aim_result_row = $aim_result_row[count($aim_result_row) - 1];
//        TODO：前端渲染路径
        $img_url = SYS_UPLOAD_URL . $aim_result_row['attachment'];
//        TODO:需要上传的地址
        $cut_pos_url = ROOT_URL . 'admin.php?s=cut&c=home&m=upload_cut_data';
        \Phpcmf\Service::V()->admin();
        \Phpcmf\Service::V()->assign([
            'img_url' => $img_url,
            'file_name' => $pure_file,
            'fileext' => $file_ext,
            'cut_pos_url' => $cut_pos_url,
            'file_id' => $aim_result_row['id'],
            'token' => dr_get_csrf_token()
        ]);
        \Phpcmf\Service::V()->display('api_cut_photo.html');
        exit;
    }

    //    TODO：修改文件名
    private function alert_file_name(&$file)
    {
//	    TODO:处理请求
        $cut_img_info = null;
//    TODO：文件名的句柄
        $img_info_handle = '';
//    TODO：文件名的数量
        $info_count = 6;
        $filename = $file['filename'];
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            $cut_img_info = json_decode($_GET['value']);
        } else {
            $cut_img_info = $_POST;

        }
        foreach ($cut_img_info['pos'] as $pos) {
            $img_info_handle .= '_' . $pos;
            $info_count--;
        }

        if ($cut_img_info['img']['width']) {
            $img_info_handle .= '_' . $cut_img_info['img']['width'];
            $info_count--;
        }

        if ($cut_img_info['img']['height']) {
            $img_info_handle .= '_' . $cut_img_info['img']['height'];
            $info_count--;
        }

        if ($info_count == 0) {
            $filename .= $img_info_handle;
            $file['filename'] = $filename;
        } else {
            //        TODO:返回
            $this->_json(1, dr_lang('文件参数错误'));
        }


    }

    //    上传文件的数据流
//admin.php?s=cut&c=home&m=upload_cut_img
    public function upload_cut_img()
    {
        $this->_check_upload_auth();
        header('Content-type:text/html;charset=utf-8');

        $base64_image_content = $_POST['file'];

//匹配出图片的格式

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {

            $type = $result[2];

            $new_file = SYS_UPLOAD_PATH . date('Ymd', time()) . "/";

            if (!file_exists($new_file)) {

//检查是否有该文件夹，如果没有就创建，并给予最高权限

                mkdir($new_file, 0700, true);

            }
            $time_tab = time();
            $new_file = $new_file . $time_tab . ".{$type}";

            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
                define('NEW_FILE', $new_file);
//                TODO:下一个控制器
                $this->upload_cut_data();
            } else {

                $this->_json(1, '文件保存失败');

            }

        }
    }
}
